const express = require('express')
const iconv = require('iconv-lite')
const app = express()

const encoding = 'binary'
const cnEncoding = 'cp936'

const child_process = require('child_process')


function runCmd(cmd) {
  const buf = child_process.execSync('bash ./a.sh')
  console.log(buf.toString())
  return buf.toString('utf8')
}

function spawn(cmd, args = []) {
  const cp = child_process.spawn(cmd, args, {maxBuffer: 5 * 1024 * 1024, encoding})
  return cp
}

app.get('/', (req, res, next) => {
  // const con = runCmd()
  res.setHeader('content-type', 'text/html; charset=utf-8')
  const cp = spawn('bash', ['a.sh'])
  res.write('<pre>')
  cp.stdout.on('data', (data) => {

    console.log('receive data:', data.toString());
    res.write(data.toString())
  })

  cp.stderr.on('error', (err) => {
    console.log('cp error:', err);
  })


  cp.on('close', (code) => {
    console.log('cmd return code::', code);
    res.end('</pre>\n')
  })
  
  // stdout.pipe(res)
  // res.end(`content output:: ${con}`)
})

app.listen(8080, () => {
  console.log('buiding server running at http://localhost:8080');
})